/**
 * 
 */
package com.roncoo.adminlte.controller.admin;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.aspectj.util.FileUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.roncoo.adminlte.bean.entity.RcDataDictionary;
import com.roncoo.adminlte.util.base.BaseController;
import com.roncoo.adminlte.util.base.PageBean;

/**
 * @author zhangliping
 *
 */
@Controller
@RequestMapping(value = "/admin/restful", method = RequestMethod.POST)
public class RestFulController extends BaseController {

	@RequestMapping(value = VIEW, method = RequestMethod.GET)
	public void list() {

	}
	
	/**
	 * 
	 * 将请求的参数存放到文件
	 * 
	 * @param dictionary
	 * @return String
	 */
	@RequestMapping(value = "",method = RequestMethod.POST)
	public String save(@RequestParam(value = "reqUrl") String reqUrl,
			@RequestParam(value = "reqMethod") String reqMethod,
			@RequestParam(value = "reqParam") String reqParam,
			@RequestParam(value = "resp") String resp,
			@RequestParam(value = "fileName") String fileName,
			ModelMap modelMap) {
		
		saveAsFile("c:/restful/" + fileName + ".txt", reqUrl, reqMethod,
				reqParam, resp);
		
		return redirect("/admin/restful/view");
	}
	
    @RequestMapping(value = "", method = { RequestMethod.POST, RequestMethod.GET })  
	public String fileDownload(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "reqUrl") String reqUrl,
			@RequestParam(value = "reqMethod") String reqMethod,
			@RequestParam(value = "reqParam") String reqParam,
			@RequestParam(value = "resp") String resp,
			@RequestParam(value = "fileName") String fileName, ModelMap modelMap) throws IOException {

		String path = "c:/restful";
		
		//判断文件名是否有后缀，如果没有后缀就添加默认后缀为txt
		if (fileName.contains(".")) {
			// 包含这个点了代表填写的时候就已经带了文件名
		}else {
			fileName = fileName + ".txt";
		}
		
		saveAsFile(path + File.separator+ fileName, reqUrl, reqMethod,
				reqParam, resp);
		response.setCharacterEncoding("utf-8");
		response.setContentType("multipart/form-data");
		response.setHeader("Content-Disposition", "attachment;fileName="
				+ fileName);
		try {
			InputStream inputStream = new FileInputStream(new File(path
					+ File.separator + fileName + ".txt"));

			OutputStream os = response.getOutputStream();
			byte[] b = new byte[2048];
			int length;
			while ((length = inputStream.read(b)) > 0) {
				os.write(b, 0, length);
			}

			 // 这里主要关闭。
			os.close();

			inputStream.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
    
    //实现文件的下载
    //需要说明的是文件的上传和下载不需要其他配置
    @RequestMapping(value = SAVE)
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session,
			@RequestParam(value = "reqUrl") String reqUrl,
			@RequestParam(value = "reqMethod") String reqMethod,
			@RequestParam(value = "reqParam") String reqParam,
			@RequestParam(value = "resp") String resp,
			@RequestParam(value = "fileName") String fileName) throws IOException{
        
        byte[] body=null;
        
		String path = "c:/restful" + File.separator+ fileName + ".txt";
		saveAsFile(path, reqUrl, reqMethod,reqParam, resp);
		
		
		InputStream in = new FileInputStream(new File(path));
        
        body=new byte[in.available()];
        in.read(body);
        
        HttpHeaders headers=new HttpHeaders();
        //响应头的名字和响应头的值
        headers.add("Content-Disposition", "attachment;filename="+ new String(fileName.getBytes("gbk"),"iso-8859-1") + ".txt");
        HttpStatus statusCode=HttpStatus.OK;
        
        ResponseEntity<byte[]> response=new ResponseEntity<byte[]>(body, headers, statusCode);
        return response;
    }
    
		
	
	/**
	 * 保存文件到C盘
	 * @param fileName 文件名
	 * @param reqUrl  请求地址
	 * @param reqMethod 请求方式
	 * @param reqParam 入参
	 * @param resp 响应
	 */
	private void saveAsFile(String fileName, String reqUrl, String reqMethod, String reqParam, String resp) {
		StringBuilder sb = new StringBuilder();
		// 处理请求地址
		if (!StringUtils.isEmpty(reqUrl)) {
			sb.append("请求地址:").append("\r\n").append(reqUrl).append("\r\n").append("\r\n");
		}
		
		// 处理请求方式
		if (!StringUtils.isEmpty(reqMethod)) {
			sb.append("请求方式:").append("\r\n").append(reqMethod).append("\r\n").append("\r\n");
		}
		
		// 处理请求参数
		if (!StringUtils.isEmpty(reqParam)) {
			sb.append("请求参数:").append("\r\n").append(reqParam).append("\r\n").append("\r\n");
		}
		
		// 处理请求结果
		if (!StringUtils.isEmpty(resp)) {
			sb.append("请求结果:").append("\r\n").append(resp).append("\r\n").append("\r\n");
		}
		// 有内容时才生成文件
		if (sb.length() > 0 ) {
			FileUtil.writeAsString(new File(fileName), sb.toString());
		}
		
	}
	
	/**
	 * 分页查询
	 * 
	 * @param start
	 * @param pageSize
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = PAGE)
	public PageBean<RcDataDictionary> queryForPage(@RequestParam(value = "start", defaultValue = "1") int start, @RequestParam(value = "length", defaultValue = "10") int pageSize, @RequestParam(value = "date", required = false) String date, @RequestParam(value = "search", required = false) String search) {
//		Result<Page<RcDataDictionary>> result = biz.listForPage((start / pageSize) + 1, pageSize, search, date);
//		if (result.isStatus()) {
//			return new PageBean<RcDataDictionary>(result.getResultData());
//		}
		return new PageBean<RcDataDictionary>();
	}
}
